import Snap from 'snapsvg-cjs'
import palletUri from '@/assets/svg/Pallet.svg'// 托盘Svg地址
import tooltipUri from '@/assets/svg/device_comment.svg'// 提示框Svg地址
import mainSvgUri from '@/assets/svg/ppk.svg'// 项目布局Svg地址
import store from '@/store/index.js'
import { zpd } from 'snap.svg.zpd'
import * as SvgConfig from './SvgConfig.js'

const hoverTimeout = 500
let vue = null
let svg = null
let group = null
let paper = null
let pallet = null
let tooltip = null
let currentHover = ''
let currentHoverEnd = false
let isComlpeted = false
let singalRData = null
let currentTips = null
const devices = {
  con: [],
  srm: [],
  rcv: [],
  other: [],
  box: [],
  srmLength: []
}
/** 初始化Svg */
export function InitSvg(value) {
  vue = value
  svg = Snap('#svg')
  svg.zpd()
  group = svg.select('g')

  SvgConfig.SetSvgStyle()

  Snap.load(mainSvgUri, (data) => group.append(data.select('svg')))
  Snap.load(tooltipUri, (data) => {
    tooltip = data.select('g')
    group.select('svg').append(tooltip)
  })
  Snap.load(palletUri, (data) => {
    pallet = data.select('g')
    group.select('svg').append(pallet)
  })

  setTimeout(() => {
    console.log(pallet, 'wwww')
    InitDevices()
  }, 500)
}
/** 处理SingalR数据推送 */
export function HandleSingalRData(value) {
  SetSingalRData(value)
  if (isComlpeted) {
    HandleConChanged()
    HandleSrmChanged()
    // HandleRgvChanged()
    HandleModeChanged()
  }
}
/** 获取推送的数据 */
export function getsingalRData() {
  return singalRData
}
/** 配置设备 */
function InitDevices() {
  paper = group.paper
  const sets = paper.selectAll('*')
  sets.forEach((el) => {
    const name = el.node.id
    if (name.indexOf('mode') > -1) SetModeDevice(el, name)
    if (name.indexOf('con') > -1) SetConDevice(el, name)
    if (name.indexOf('srm') > -1) SetSrmDevice(el, name)
    // if (name.indexOf('rgv') > -1) SetRgvDevice(el, name)
    if (name.indexOf('trail') > -1) SetSrmTrail(el, name)
    if (name.indexOf('shelf') > -1) SetSrmThelf(el, name)
  })
  isComlpeted = true
}
/** 设置Srm路径长度 */
function SetSrmTrail(el, name) {
  // console.log(el, name, 'SetSrmTrail');
  const width = el.node.width.baseVal.value
  const height = el.node.height.baseVal.value
  devices.srmLength.push({
    name,
    length: width > height ? width : height
  })
  // console.log(devices.srmLength)
}

/** 设置Srm设备 */
function SetSrmDevice(el, name) {
  devices.srm.push(el)
  el.click(function () {
    SrmClick(name)
  })
  // el.hover(
  //   function () {
  //     DeviceHover(name, 'srm', el)
  //   },
  //   function () {
  //     DeviceHoverOff()
  //   }
  // )
}
/** 设置Rgv设备 */
function SetRgvDevice(el, name) {
  devices.rgv.push(el)
  el.click(function () {
    RgvClick(name)
  })
}
/** 设置输送线设备 */
function SetConDevice(el, name) {
  // console.log(el, name);
  devices.con.push(el)
  el.click(function () {
    ConClick(name)
  })
  el.hover(
    function () {
      DeviceHover(name, 'con', el)
    },
    function () {
      DeviceHoverOff()
    }
  )
  CreateSvgText(paper, name, 48, el)
}
/** 悬停 */
function DeviceHover(name, type, el) {
  if (!isComlpeted) return
  const hoverFlag = name
  currentHover = hoverFlag
  currentHoverEnd = true
  const tipsEl = group.select(`#hover-tips`)
  if (tipsEl !== null) tipsEl.remove()
  setTimeout(() => {
    if (currentHover === hoverFlag && currentHoverEnd) {
      try {
        console.log(tooltip, 'tooltip')
        currentTips = tooltip
          .clone()
          .attr({ id: 'hover-tips', display: 'block' })
      } catch (error) {
        return
      }
      SetTooltip(el, type)
    }
  }, hoverTimeout)
}
/** 解除悬停 */
function DeviceHoverOff() {
  if (!isComlpeted) return
  currentHoverEnd = false
  if (currentTips !== null) {
    currentTips.remove()
    currentTips = null
  }
}
/** 设置悬浮弹窗内容 */
function SetTooltip(el, type) {
  console.log(el, 'el', type);
  const sets = currentTips.selectAll('*')
  const posi = SvgConfig.GetElementRightTop(el)
  sets.forEach(function (el, index) {
    const type = el.type
    if (type === 'path') {
      el.attr({
        d: `M${posi.x},${posi.y} h1200 v450 h-950 L${posi.x + 250
          },${posi.y + 150} z`
      })
    } else if (type === 'text') {
      el.attr({
        x: posi.x + 300,
        y: posi.y + index * 100
      })
    }
  })

  let currentData = null
  if (type === 'con') {
    currentData = singalRData.con.find(
      (item) => ('con' + item.name) === el.node.id
    )
    // console.log(currentData, 'currentData');
  } else if (type === 'srm') {
    currentData = singalRData.srm.find(
      (item) => item.name === el.node.id
    )
  }

  if (!(currentData === undefined || currentData === null)) {
    sets[1].node.innerHTML += currentData.des
    sets[2].node.innerHTML += currentData.unitId
    sets[3].node.innerHTML += SvgConfig.GetModeMappingData(currentData.mode)
  }
}
/** 设置模式灯，存储 */
function SetModeDevice(el, name) {
  devices.other.push(el)
  el.click(function () {
    // let singalRData = getsingalRData()
    const newdata = singalRData.other.find(item => item.name === name)
    // console.log('name', name, 2, newdata)
    vue.IOPortData = newdata
    SetDialogProperty(name, 2)
  })
}
/** 设置货架 */
function SetSrmThelf(el, name) {
  // devices.srm.push(el)
  if (name === 'shelf01' || name === 'shelf02') {
    el.click(function () {
      console.log(el, name, '1-2');
      vue.$router.push('/LocInnerManage/LocMonitor')
    })
  } else if (name === 'shelf03' || name === 'shelf04') {
    el.click(function () {
      console.log(el, name, '3-4');
      vue.$router.push('/LocInnerManage/LocMonitor')
    })
  }

}

/** 创建SVG   Text
 * @param {*} paper SVG paper
 * @param {*} name text内容
 * @param {*} size 字体大小
 * @param {*} el 在目标元素上显示
 */
function CreateSvgText(paper, name, size, el) {
  var textSplit
  //将获取到的text内容去除con
  if ((name.indexOf('con') > -1)) {
    textSplit = name.replace('con', '')
  }
  if ((name.indexOf('srm') > -1)) {
    textSplit = name.replace('con', '')
  }
  const t = paper.text(0, 0, textSplit).attr({
    fill: '#fff',
    'font-size': size,
    x: el.node.x.baseVal.value + 5,
    y: el.node.y.baseVal.value + size,
  })
  t.insertAfter(el)
}

/** 设置SingalR的数据 */
function SetSingalRData(value) {
  // console.log(value);
  singalRData = {
    con: value.monitorConDatas,
    srm: value.monitorSrmDatas,
    // rgv: value.monitorSrmDatas,
    other: value.monitorOtherDatas
  }
}
/** 处理Con数据变化 */
function HandleConChanged() {
  // console.log('HandleConChanged', singalRData.con);
  singalRData.con.forEach((data) => {
    const dev = devices.con.find((item) => item.node.id === ('con' + data.name))
    if (dev) {
      const color = SvgConfig.GetModeColor(data.mode)

      const boxName = data.name + '_box'
      if (data.unitId.length > 0) {
        AddGoods(boxName, dev)
      } else {
        RemoveGoods(boxName)
      }


      let light_in = document.getElementById(`${data.name}-light-in`)
      let light_out = document.getElementById(`${data.name}-light-out`)
      if (light_in && light_out) {
        if (data.direction === 1) {
          light_in.setAttribute('display', "block")
          light_out.setAttribute('display', 'none')
        }
        else if (data.direction === 2) {
          light_in.setAttribute('display', "none")
          light_out.setAttribute('display', 'block')
        } else if (data.direction === 3) {
          light_in.setAttribute('display', "block")
          light_out.setAttribute('display', 'block')
        } else {
          light_in.setAttribute('display', "none")
          light_out.setAttribute('display', 'none')
        }
      }

      SvgConfig.DoColorAnimate(dev, color)
    }
  })
}
// function HandleConChanged() {
//   // console.log('HandleConChanged',singalRData.con,devices.con);
//   singalRData.con.forEach((data) => {
//     const dev = devices.con.find((item) => item.node.id === ('con' + data.name))
//     if (dev) {
//       const color = SvgConfig.GetModeColor(data.mode)

//       const boxName = data.name + '_box'
//       if (data.unitId.length > 0) {
//         AddGoods(boxName, dev)
//       } else {
//         RemoveGoods(boxName)
//       }
//       SvgConfig.DoColorAnimate(dev, color)
//     }
//   })
// }
/** 处理Srm数据变化 */
function HandleSrmChanged() {
  singalRData.srm.forEach((data) => {
    const dev = devices.srm.find((item) => item.node.id === ('srm' + data.name))
    // console.log('srmData => \r\n', singalRData.srm,data,devices.srm);
    if (dev) {
      const color = SvgConfig.GetModeColor(data.mode)
      // console.log(devices, 'devices', dev.node.id,data);
      const matrix = GetTrailPosition(data.bayNum, ('srm' + data.name)) // 获取轨道位置
      // console.log('HandleSrmChanged', color, matrix, dev);

      const boxName = data.name + '_box'
      const box = GetBox(boxName, dev)
      if (data.unitId.length > 0) {
        AddGoods(boxName, dev)
      } else {
        RemoveGoods(boxName)
      }
      SvgConfig.DoPositionAnimate(dev, matrix)
      SvgConfig.DoPositionAnimate(box, matrix)
      SvgConfig.DoColorAnimate(dev, color)
    } else {
      console.log(`error,未找到${data.name}`)
    }
  })
}
/** 处理Rgv数据变化 */
function HandleRgvChanged() {
  singalRData.rgv.forEach((data) => {
    const dev = devices.rgv.find((item) => item.node.id === data.name)
    // console.log('rgvData => \r\n', singalRData.rgv, data);
    if (dev) {
      const color = SvgConfig.GetModeColor(data.mode)
      // console.log(devices, 'devices', dev.node.id,data);
      const matrix = GetTrailPosition(data.bayNum, data.name) // 获取轨道位置
      // console.log('HandleRgvChanged', color, matrix,dev);

      const boxName = data.name + '_box'
      const box = GetBox(boxName, dev)
      if (data.unitId.length > 0) {
        AddGoods(boxName, dev)
      } else {
        RemoveGoods(boxName)
      }
      SvgConfig.DoPositionAnimate(dev, matrix)
      SvgConfig.DoPositionAnimate(box, matrix)
      SvgConfig.DoColorAnimate(dev, color)
    } else {
      console.log(`error,未找到${data.name}`)
    }
  })
}
/** 处理Mode数据变化 */
function HandleModeChanged() {
  singalRData.other.forEach((data) => {
    const dev = devices.other.find((item) => item.node.id === data.name)
    // console.log(data, '12345678', dev)
    const color = data.mode ? '#67C23A' : '#F56C6C'
    SvgConfig.DoColorAnimate(dev, color)
  })
}
/** 获取堆垛机当前所在位置 */
function GetTrailPosition(bayNum, srmName) {
  // console.log(bayNum,srmName);
  let srmTrailName
  if (srmName === 'srmCJSTW100-C1') {
    srmTrailName = 'trail01'
  } else if (srmName === 'srmCJSTW100-C2') {
    srmTrailName = 'trail02'
  } else if (srmName === 'srmCJSTW200-C1') {
    srmTrailName = 'trail03'
  } else if (srmName === 'srmCJSTW200-C2') {
    srmTrailName = 'trail04'
  }
  // srmTrailName = srmName.replace('srm', 'trail')
  const lengthObj = devices.srmLength.find((x) => x.name === srmTrailName)
  // console.log(srmTrailName, devices.srmLength, lengthObj, 'lengthObj');
  const length = lengthObj.length
  const matrix = new Snap.Matrix(1, 0, 0, 1, 0, 0)
  const p = (bayNum / 100) * length
  matrix.add(1, 0, 0, 1, 0, -p)
  return matrix
}
/** 添加货物（托盘）
 * @param {*} boxName Svg标签托盘ID
 * @param {*} el 设备Svg
 */
function AddGoods(boxName, el) {
  const box = GetBox(boxName, el)
  box.attr({ display: 'block' })
}
/** 移除货物
 * @param {*} boxName 货物Id
 */
function RemoveGoods(boxName) {
  const box = document.getElementById(boxName)
  if (box !== undefined && box !== null) {
    box.style.display = 'none'
  }
}
/** 获取货物图形
 * @param {*} boxName
 * @param {*} el 设备Element
 * @returns box
 */
function GetBox(boxName, el) {
  let box = group.select(`#${boxName}`)
  if (box === undefined || box === null) {
    box = pallet.clone().attr({ id: boxName, display: 'block' })
    const appearance = SvgConfig.GetDeviceAppearance(el)
    const subbox = box.selectAll('*')
    subbox[0].attr({
      x: appearance.pos.x + 10,
      y: appearance.pos.y + 10,
      width: appearance.size,
      height: appearance.size
    })
    subbox[1].attr({
      x: appearance.pos.x,
      y: appearance.pos.y,
      width: appearance.size,
      height: appearance.size
    })
  }
  return box
}
/** 输送设备点击 */
function ConClick(name) {
  SetDialogProperty(name, 0)
}
/** 堆垛机设备点击 */
function SrmClick(name) {
  SetDialogProperty(name, 1)
  vue.disableClickShow = true
  const nowsrm = singalRData.srm.find((item) => item.name === name)
  console.log(nowsrm, 'nowsrm', singalRData.srm)
  if (nowsrm) vue.errorCode = nowsrm.errorCode
}
/** rgv设备点击 */
function RgvClick(name) {
  SetDialogProperty(name, 1)
  vue.disableClickShow = true
  const nowsrm = singalRData.rgv.find((item) => item.name === name)
  console.log(nowsrm, 'nowsrm', singalRData.srm)
  if (nowsrm) vue.errorCode = nowsrm.errorCode
}
/** 设置Dialog属性 */
function SetDialogProperty(name, option) {
  vue.particularsclick = false
  vue.errorCode = 0
  vue.dialogVisible = true
  vue.dialogTitle = name
  vue.dialogOption = option
}

